// src/components/popups/userActions/UpdateInfo.tsx

import { useState, useEffect } from 'react';
import type { FC } from 'react';
import { updateUserProfile } from '@/services/authService';
import type { UpdateProfileRequest } from '@/types/types';
import { useUserStore } from '@/store/userStore';

interface UpdateInfoProps {
  firstName: string;
  lastName: string;
  email: string;
  onClose: () => void;
  onUpdateUser: (updated: {
    first_name?: string;
    last_name?: string;
    email?: string;
  }) => void;
}

const UpdateInfo: FC<UpdateInfoProps> = ({
  firstName: initFirst,
  lastName: initLast,
  email: initEmail,
  onClose,
  onUpdateUser,
}) => {
  const [firstName, setFirstName] = useState(initFirst);
  const [lastName, setLastName] = useState(initLast);
  const [email, setEmail] = useState(initEmail);
  const [emailError, setEmailError] = useState('');
  const [isDirty, setIsDirty] = useState(false);
  const [message, setMessage] = useState('');
  const [showMessage, setShowMessage] = useState(false);
  const { setUser } = useUserStore();

  useEffect(() => {
    setIsDirty(
      firstName !== initFirst || lastName !== initLast || email !== initEmail
    );
  }, [firstName, lastName, email, initFirst, initLast, initEmail]);

  const handleSubmit = async () => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setEmailError('Invalid email format');
      return;
    }

    setEmailError('');
    const token = localStorage.getItem('token');
    if (!token) return;

    const payload: UpdateProfileRequest = {
      first_name: firstName,
      last_name: lastName,
      email,
    };

    try {
      await updateUserProfile(payload, token);

      setUser((prev) => ({
        ...prev,
        firstName,
        lastName,
        email,
      }));

      onUpdateUser(payload);

      setMessage('Profile updated successfully!');
      setShowMessage(true);
      setTimeout(() => {
        setShowMessage(false);
        onClose();
      }, 1500);
    } catch {
      setMessage('Failed to update profile.');
      setShowMessage(true);
      setTimeout(() => setShowMessage(false), 2000);
    }
  };

  return (
    <div className="p-6 sm:p-8 space-y-6 text-gray-800 dark:text-gray-100 font-poppins">
      {showMessage && (
        <div className="fixed top-6 left-1/2 transform -translate-x-1/2 bg-indigo-600 dark:bg-cyan-700 text-white px-4 py-2 rounded-xl shadow-lg z-50 animate-fade-in">
          {message}
        </div>
      )}

      <h2 className="text-xl sm:text-2xl font-semibold text-center text-gray-800 dark:text-cyan-200">Update Info</h2>

      <div className="space-y-5">
        <div>
          <label className="block text-sm font-medium text-gray-600 dark:text-gray-300 mb-1">First Name</label>
          <input
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 dark:border-slate-700 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:focus:ring-cyan-700 bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-600 dark:text-gray-300 mb-1">Last Name</label>
          <input
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 dark:border-slate-700 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:focus:ring-cyan-700 bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-600 dark:text-gray-300 mb-1">Email</label>
          <input
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className={`w-full px-4 py-2 border rounded-xl shadow-sm focus:outline-none bg-white dark:bg-slate-800 text-gray-800 dark:text-gray-100 ${emailError
              ? 'border-red-500 ring-1 ring-red-400 dark:ring-red-600'
              : 'border-gray-300 dark:border-slate-700 focus:ring-2 focus:ring-indigo-500 dark:focus:ring-cyan-700'
              }`}
          />
          {emailError && <p className="text-sm text-red-500 dark:text-red-400 mt-1">{emailError}</p>}
        </div>
      </div>

      <div className="flex justify-end mt-6 gap-3">
        <button
          onClick={onClose}
          className="px-4 py-2 rounded-xl border border-gray-300 dark:border-slate-700 text-gray-600 dark:text-gray-200 hover:text-gray-800 dark:hover:text-cyan-300 bg-white dark:bg-slate-800 transition"
        >
          Back
        </button>
        <button
          onClick={handleSubmit}
          disabled={!isDirty}
          className={`px-6 py-2 rounded-xl text-white font-medium transition ${isDirty
            ? 'bg-indigo-600 dark:bg-cyan-700 hover:bg-indigo-700 dark:hover:bg-cyan-800 shadow-md'
            : 'bg-gray-400 dark:bg-slate-700 cursor-not-allowed'
            }`}
        >
          Confirm
        </button>
      </div>
    </div>
  );
};

export default UpdateInfo;